package com.jic.member.sms;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.StringWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

public class TmpltHelper {

    private static TmpltHelper instance = new TmpltHelper();
    private static VelocityEngine ve;

    static {
        Properties props = new Properties();
        props.setProperty("input.encoding", "UTF-8");
        props.setProperty("resource.loader", "class");
        props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.init(props);
        ve = velocityEngine;
    }

    public TmpltHelper() {
    }

    public static TmpltHelper getInstance() {
        return instance;
    }

    public String forMatContent(Map<String, String> varMap, String tmpltContent) throws Throwable {
        if (varMap != null && varMap.size() != 0) {
            if (tmpltContent == null) {
                throw new Throwable("varTmplt nullpoitException!");
            } else {
                VelocityContext ctx = new VelocityContext();
                Iterator i = varMap.keySet().iterator();

                while(i.hasNext()) {
                    String key = (String)i.next();
                    ctx.put(key, varMap.get(key));
                }

                StringWriter writer = new StringWriter();
                ve.evaluate(ctx, writer, "", tmpltContent);
                writer.close();
                return writer.toString();
            }
        } else {
            throw new Throwable("varMap nullpoitException!");
        }
    }
}
